<!--
 * @Description: 列表表头
 * @Author: seadon
 * @LastEditors: seadon
 * @Date: 2021-04-19 11:59:02
 * @LastEditTime: 2022-09-20 14:24:11
-->
<template>
	<div :class="{ 'header-cell': true, ['editable']: column.editHeader }">
		<div v-if="column.editHeader" class="header-edit">
			<a-select v-bind="getComponentProps" @change="handleChange"></a-select>
		</div>
		<a-tooltip :title="getTitle">
			<span class="header-title">{{ getTitle }}</span>
		</a-tooltip>
	</div>
</template>
<script lang="ts">
import { defineComponent, computed, PropType, unref, ref, Ref } from 'vue'
import { keyBy } from 'lodash'
import { useTableContext } from '../hooks/useTableContext'
import type { BasicColumn } from '../types/table'

export default defineComponent({
	name: 'HeaderCell',
	props: {
		column: {
			type: Object as PropType<BasicColumn>,
			default: () => ({}),
		},
	},
	setup(props) {
		const changeRef: Ref<Recordable<string | number>> = ref({})
		const table = useTableContext()
		const getTitle = computed(() => props.column?.customTitle)
		const getComponentProps = computed(() => {
			let compProps = props.column?.editComponentProps ?? {}
			let dict: Recordable = {}
			if (compProps.options?.length) {
				dict = keyBy(compProps.options, 'value')

				compProps = {
					...compProps,
					options: compProps.options.filter(
						(item: Recordable) => !item.hide && !item.disabled
					),
				}
			}

			return {
				...compProps,
				value:
					dict[
						unref(changeRef)[unref(getTitle) as string] ||
							(props.column.customTitleSelect as string)
					]?.label || props.column.customTitleSelect,
			}
		})

		const handleChange = (value: string, option: any) => {
			unref(changeRef)[unref(getTitle) as string] = value

			table.emit?.('header-change', {
				value,
				title: unref(getTitle),
			})
		}

		return { getTitle, getComponentProps, handleChange }
	},
})
</script>

<style lang="less" scoped>
.header-cell {
	display: inline-block;
	white-space: nowrap;
	text-overflow: ellipsis;
	overflow: hidden;

	&.editable {
		margin-bottom: -6px;
		height: 68px;
		& > .header-title {
			display: inline-block;
			margin-top: 48px;
		}
	}
}
.header-edit {
	position: absolute;
	width: calc(100% - 16px);
	display: flex;
	flex-direction: column;

	&::after {
		content: '';
		margin: 8px -8px 0;
		border-bottom: solid 1px #dadbdf;
	}
}
</style>
